package com.bang.controller;

import com.bang.pojo.Books;
import com.bang.pojo.User;
import com.bang.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/book")
public class BookController {

    @Autowired
    @Qualifier("BookServiceImpl")
    private BookService bookService;

    @RequestMapping("/find")
    public String selByNameAndPwd(String uname,String upassword,Model model){
        //control+alt+v 自动补全返回值！！！！
        User user = bookService.queryByNameAndPwd(uname, upassword);
        String message="<meta http-equiv='refresh' content='3;url=/index.jsp'>3秒钟后会自动调到首页，如果未跳转请点击<a href='/index.jsp'>跳转链接</a><hr>温馨提示：<br/>您的账号或密码不正确！";
        if (user==null){
            model.addAttribute("errorMessage",message);
            return "error";
        }
        return "redirect:/book/allBook";
    }

    @RequestMapping("/allBook")
    public String list(Model model) {
        List<Books> list = bookService.queryAllBook();
        model.addAttribute("list",list);
        return "allBook";
    }

    @RequestMapping("/toAddBook")
    public String toAddPaper() {
        return "addBook";
    }

    @RequestMapping("/addBook")
    public String addPaper(Books books) {
        bookService.addBook(books);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/toUpdateBook")
    public String toUpdateBook(Model model, int id) {
        Books books = bookService.queryBookById(id);
        model.addAttribute("book",books );
        return "updateBook";
    }

    @RequestMapping("/updateBook")
    public String updateBook(Books book) {
        bookService.updateBook(book);
        return "redirect:/book/allBook";
    }

    @RequestMapping("/del/{bookId}")
    public String deleteBook(@PathVariable("bookId") int id) {
        bookService.deleteBookById(id);
        return "redirect:/book/allBook";
    }
    @RequestMapping("/queryBook")
    public String queryByName(String bookName,Model model){
        List<Books> books=bookService.queryBookByName(bookName);
        List<Books> list=new ArrayList<Books>();
        if (bookName==null || bookName==""){
            list=bookService.queryAllBook();
            model.addAttribute("error","您未输入书籍名称!");
            model.addAttribute("list",list);
            return "allBook";
        }
        for (Books book : books){
            list.add(book);
        }

        model.addAttribute("list",list);
        return "allBook";

    }

}
